package com.mk.mq;

import com.mk.entity.Chat;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

/**
 * RabbitMQ的消息生产者
 */
@Service
public class MessageSender {
    private final RabbitTemplate rabbitTemplate;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public MessageSender(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    public void sendMessage(Chat chat) {
        try {
            String messageJson = objectMapper.writeValueAsString(chat);
            rabbitTemplate.convertAndSend("chat.exchange", "chat.route." + chat.getReceiveUserId(), messageJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
